#!/usr/bin/env node
'use strict';

const { MongoClient } = require('../..');
const visualizeMonitoringEvents = require('./utils').visualizeMonitoringEvents;
const chalk = require('chalk');
const argv = require('yargs')
  .usage('Usage: $0 [options] <connection string>')
  .demandCommand(1)
  .help('h')
  .describe('workload', 'Simulate a read workload')
  .alias('w', 'workload')
  .alias('h', 'help').argv;

function print(msg) {
  console.log(`${chalk.white(new Date().toISOString())} ${msg}`);
}

const uri = argv._[0];
const client = new MongoClient(uri);

async function run() {
  print(`connecting to: ${chalk.bold(uri)}`);

  visualizeMonitoringEvents(client);
  await client.connect();

  if (argv.workload) {
    scheduleWorkload(client);
  }
}

let workloadTimer;
let workloadCounter = 0;
let workloadInterrupt = false;
async function scheduleWorkload(client) {
  if (!workloadInterrupt) {
    // immediately reschedule work
    workloadTimer = setTimeout(() => scheduleWorkload(client), 7000);
  }

  const currentWorkload = workloadCounter++;

  try {
    print(`${chalk.yellow(`workload#${currentWorkload}`)} issuing find...`);
    const result = await client
      .db('test')
      .collection('test')
      .find({}, { socketTimeout: 2000 })
      .limit(1)
      .toArray();

    print(
      `${chalk.yellow(`workload#${currentWorkload}`)} find completed: ${JSON.stringify(result)}`
    );
  } catch (e) {
    print(`${chalk.yellow(`workload#${currentWorkload}`)} find failed: ${e.message}`);
  }
}

let exitRequestCount = 0;
process.on('SIGINT', async function() {
  exitRequestCount++;
  if (exitRequestCount > 3) {
    console.log('force quitting...');
    process.exit(1);
  }

  workloadInterrupt = true;
  clearTimeout(workloadTimer);
  await client.close();
});

run().catch(error => console.log('Caught', error));
